<?php

class AdminModel extends CI_Model {
 
    public function __construct()
    {
        parent::__construct();
    }
	
	public function doesDVDExist($dvd_id)
	{
		if(!is_numeric($dvd_id))
		{
			return false;
		}
		$query = $this->db->get_where('dvds', array('dvd_id' => $dvd_id));
		return $query->num_rows != 0;
	}
	
	public function addDVD()
	{
		$upload_data = $this->upload->data();
		$data = array(
			'dvd_title' => $this->input->post('dvd_title'),
			'dvd_price' => $this->input->post('dvd_price'),
			'dvd_cover' => $upload_data['file_name']
		);
		$this->db->insert('dvds', $data);
		
		$this->resizeCover(dvd_covers_path().$upload_data['file_name']);
	}
	
	public function updateDVD($dvd_id, $file_uploaded)
	{
		$upload_data = $this->upload->data();
		$data = array(
			'dvd_title' => $this->input->post('dvd_title'),
			'dvd_price' => $this->input->post('dvd_price')
		);
		if($file_uploaded)
		{
			$data['dvd_cover'] = $upload_data['file_name'];
		}
		$this->db->where('dvd_id', $dvd_id);
		$this->db->update('dvds', $data);
		
		if($file_uploaded)
		{
			$this->resizeCover(dvd_covers_path().$upload_data['file_name']);
		}
	}
	
	public function deleteDVD($dvd_id)
	{
		$query = $this->db->get_where('dvds', array('dvd_id' => $dvd_id));
		$result = $query->result();
		$row = $result[0];
		
		$this->db->delete('dvds', array('dvd_id' => $dvd_id));
		unlink(dvd_covers_path().$row->dvd_cover);
	}
	
	
	private function resizeCover($srcPath)
	{
		$config['image_library'] = 'gd2';
		$config['width'] = 80;
		$config['height'] = 80;
		$config['master_dim'] = 'height';
		$config['maintain_ratio'] = true;
		$config['source_image'] = $srcPath;
		$this->load->library('image_lib', $config);
		$this->image_lib->resize();
	}
}